#include "clientconfig.h"
#include "ui_clientconfig.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QMouseEvent>

clientconfig::clientconfig(QDialog *parent) :
    QDialog(parent),
    ui(new Ui::clientconfig)
{
    ui->setupUi(this);
    // 固定登录大小窗口
    this->setFixedSize(300, 400);
    // 设置登录窗口无边框
    this->setWindowFlags(Qt::FramelessWindowHint);
    // json文件单例对象
    FileOperation *op = FileOperation::getInstance();
    // 监听打开文件
    connect(ui->OpenFile,&QPushButton::clicked, this,[&](){
        // 模态方式选取文件筐
        QString path = QFileDialog::getOpenFileName(this, "打开文件");
        // 显示路径
        ui->Path->setText(path);
        // 尝试读取配置文件
        op->readConif(&cl_cfg);
        ui->Address->setText(cl_cfg.ip);
        ui->Name->setText(cl_cfg.username);
        ui->Password->setText(cl_cfg.password);
        ui->Port->setText(cl_cfg.port);
    });
    // 监听返回按钮
    connect(ui->Back, &QPushButton::clicked, this, [&](){
        // 发送信号
        emit sendUserPwd(cl_cfg.username,cl_cfg.password);
        // 隐藏
        this->hide();
    });

    // 监听保存
    connect(ui->Save, &QPushButton::clicked, this, [&](){
        cl_cfg.ip = ui->Address->text();
        cl_cfg.username = ui->Name->text();
        cl_cfg.filepath = ui->Path->text();
        cl_cfg.port = ui->Port->text();
        cl_cfg.password = ui->Password->text();
        op->writeConfig(cl_cfg);
        // 弹出保存成功提示
        QMessageBox::information(nullptr,  "result",  "save ok!", QMessageBox::Yes, QMessageBox::Yes);
    });

    if(op->readConif(&cl_cfg))
    {
        ui->Address->setText(cl_cfg.ip);
        ui->Name->setText(cl_cfg.username);
        ui->Path->setText(cl_cfg.filepath);
        ui->Password->setText(cl_cfg.password);
        ui->Port->setText(cl_cfg.port);
    }
}

clientconfig::~clientconfig()
{
    delete ui;
}


void clientconfig::mouseMoveEvent(QMouseEvent *event)
{
    if(mouse_press)
    {
        move(event->globalPos() - mousePoint);
    }
}

void clientconfig::mousePressEvent(QMouseEvent *event)
{
    // 如果点击鼠标左键
    if(event->button() == Qt::LeftButton){
        mouse_press = true;
        // 鼠标点击的位置 - 窗口坐标
        mousePoint = event->globalPos() - this->pos();
    }
}

void clientconfig::mouseReleaseEvent(QMouseEvent*)
{
    mouse_press = false;
}
